<?php
abstract class BaseController extends Controller {
	
	protected $table = '';
	protected $tabs = array();
	
	protected function init() {
	if (!$this->userid && CONTROL_NAME != 'Account' && ACTION_NAME != 'login') {
			$this->redirect(url('account.login'), 0);
		}
	}
	
	protected function prompt($msg, $url='') {
		if ($url) {
			$jumpurl = "window.location='{$url}'";
		} else {
			$jumpurl = "history.back();";
		}
		$this->assign('msg', $msg);
		$this->assign('jumpurl', $jumpurl);
		$this->display('prompt');
		exit();
	}
	
	/**
	 * 添加页面选项卡
	 */
	public function addTab($name, $method, $query = '') {
		$this->tabs[$name] = array($method, $query);
	}
	
	/**
	 * 显示选项卡
	 */
	public function showTabs() {
		$arr = array();
		$out = '<div class="tab">';
		$out .= '<ul>';
		
		foreach ($this->tabs as $name => $url) {
			$css = '';
			if (!strcasecmp(CONTROL_NAME.'.'.ACTION_NAME, $url[0])) {
				$css = 'class="on"';
				if (!empty($url[1])) {
					if (!is_array($url[1])) parse_str(ltrim($url[1], '?'), $url[1]);
					foreach ($url[1] as $var => $val) {
						if ($this->input->get($var) != $val) {
							$css = ''; break;
						}
					}
				}
			}
			$out .= sprintf('<li><a href="%s" %s>%s</a></li>', URL($url[0], $url[1]), $css, $name);
		}
		$out .= '</ul>';
		$out .= '</div>';
		echo $out;
	}
	
	/**
	 * 显示分类下拉列表
	 * @param string $type 类型
	 * @param int $selid 默认选中的分类ID
	 * @param int $deep 显示深度
	 */
	public function showCateOptions($type, $selid=0, $deep=0) {
		$parents = $children = array();
		$wheresql = '';
		
		if ( $deep == 1 ) {
			$wheresql = ' AND parentid = 0';
		}
		$sql = "SELECT id,parentid,children,catename,`count`,orderid " .
				"FROM ".$this->db->getTable('cate')." " .
				"WHERE `type` = '{$type}' {$wheresql} ORDER BY parentid,orderid";
		$list = $this->db->getList($sql);
		foreach ($list as $row) {
			if (!$row['parentid'] ) {
				$parents[] = $row;
			} else {
				$row['catename'] = '&nbsp;&nbsp;&nbsp;&nbsp;|-'.$row['catename'];
				$children[$row['parentid']][] = $row;
			}
		}

		$output = '';
		foreach ( $parents as $row ) {
			$selstr = $row['id'] == $selid ? ' selected="selected"' : '';
			if ( $row['children'] ) {
				$selstr .= ' class="parent_option"';
			}
			$output .= '<option value="'.$row['id'].'"'.$selstr.'>'.$row['catename'].($row['children']?'':'('.$row['count'].')').'</option>';
			if ( isset($children[$row['id']]) ) {
				foreach ( $children[$row['id']] as $child ) {
					$selstr = $child['id'] == $selid ? ' selected="selected"' : '';
					$output .= '<option value="'.$child['id'].'"'.$selstr.'>'.$child['catename'].' ('.$child['count'].')</option>';
				}
			}
		}
		echo $output;
	}
}
?>